package modelo.bd;

import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Conexion {

    private static Conexion instancia;
    private Configuracion config;
    private Connection con;
    private Statement sentencia;
    private CallableStatement cstmt;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return new CloneNotSupportedException("No se pueden clonar Conexiones");
    }

    private Conexion() {
        this.config = new Configuracion();
    }

    public static Conexion instancia() {
        if (instancia == null) {
            instancia = new Conexion();
        }
        return instancia;
    }

    public void crear() throws ClassNotFoundException, SQLException {
        Class.forName(config.getDriver());
        con = DriverManager.getConnection(config.getUrl(), config.getUsuario(), config.getContrasenia());
    }

    public void ejecutarActualizacion(String query) throws SQLException {
        try {
            sentencia = con.createStatement();
            sentencia.executeUpdate(query);
        } catch (SQLException ex) {
            reiniciar();
            throw new SQLException(ex);
        }
    }

    public ResultSet ejecutarConsulta(String query) throws SQLException {
        try {
            sentencia = con.createStatement();
            ResultSet rs = sentencia.executeQuery(query);
            return rs;
        } catch (SQLException ex) {
            reiniciar();
            throw new SQLException(ex);
        }
    }

    public ResultSet ejecutarStored(String query) throws SQLException {
        try {
            cstmt = con.prepareCall(query);
            cstmt.execute();
            ResultSet rs = cstmt.getResultSet();
            return rs;
        } catch (SQLException ex) {
            reiniciar();
            throw new SQLException(ex);
        }
    }

    public void reiniciar() throws SQLException{
        con.close();
        try {
            this.crear();
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public void cerrar() throws SQLException{
        con.close();
    }
}
